<template>
  <div class="form-editor-wrap">
    <quill-editor
        ref="editor"
        class="editor"
        v-model="content"
        :options="editorOption"
        @change="handleEditorChange($event)"
    />
    <el-upload
        v-if="false"
        :action="uploadUrl"
        :multiple="false"
        :show-file-list="false"
        :headers="headers"
        ref="publicUploader"
        class="public-uploader"
        :before-upload="beforeUpload"
        :on-progress="uploadProgress"
        :on-change="uploadChange"
        :accept="format"
    />
    <SelectPicture
        :visible="pictureInfo.visible"
        :info="pictureInfo.info"
        @handleCancel="handleCancel"
        @handleSure="handlePictureSure"
    />
  </div>
</template>

<script>
import {apiRoot} from "@/services/ajax";
import SelectPicture from "@/components/public/layer/template/selectPicture";


const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用  代码块
  [{header: 1}, {header: 2}], // 1、2 级标题
  [{list: "ordered"}, {list: "bullet"}], // 有序、无序列表
  [{script: "sub"}, {script: "super"}], // 上标/下标
  [{indent: "-1"}, {indent: "+1"}], // 缩进
  [{'direction': 'rtl'}],                         // 文本方向
  [{size: ["small", false, "large", "huge"]}], // 字体大小
  [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题
  [{color: []}, {background: []}], // 字体颜色、字体背景颜色
  [{align: []}], // 对齐方式
  ["clean"],     // 清除文本格式
  ["link", "image"] // 链接、图片、视频
];

const headers = Object();
Reflect.set(headers, "Content-Type", "multipart/form-data");
Reflect.set(headers, "responseType", "blod");// "arraybuffer" 或者 "blod"，告诉服务器以二进制方式返回
export default {
  name: 'Formeditor',

  props: ["contentInfo"],

  components: {
    SelectPicture
  },

  data() {
    return {
      fileList: [],
      format: '.jpg,.jpeg,.png',
      content: null,
      headers: headers,
      loading: false,
      upFile: new FormData(),
      id: (this.$route.params.id),
      pictureInfo: {
        visible: false,
        info: 1,
      },
      uploadUrl: `${apiRoot('/upload', 'BaseApi')}`, 	// 服务器上传地址
      editorOption: {
        placeholder: '请在这里添加产品描述...', //提示
        readyOnly: false, //是否只读
        theme: 'snow', //主题 snow/bubble
        syntax: true, //语法检测
        modules2: {
          toolbar: {
            container: toolbarOptions,
            handlers: {
              self: this,
              image: function (value) {
                if (value) {
                  this.format = '.jpg,.jpeg,.png';
                  Reflect.set((this.handlers.self.$data.pictureInfo), 'visible', true);
                  Reflect.set((this.handlers.self.$data.pictureInfo), 'info', 1);
                  console.log((this.handlers.self.$data.pictureInfo))
                  // 调用的图片上传组件
                  // document.querySelector('.public-uploader input').click();
                } else {
                  this.quill.format('image', false)
                }
              }
            },
          },
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          imageDrop: false,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        },
      }
    }
  },

  methods: {
    //上传前验证图片大小和图片格式
    beforeUpload(file, fileList) {
      const self = this;
      self.fileList = fileList
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['jpg', 'png', 'jpeg']
      const isSuffix = whiteList.indexOf(fileSuffix.toLowerCase()) === -1
      const isLt5M = file.size / 1024 / 1024 > 5;
      if (isSuffix) {
        this.$message.error('上传图片格式只能是 jpg、jpeg、png');
        return true;
      }
      if (isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB');
        return true;
      }
      return !isSuffix && !isLt5M;
    },

    // 上传的进度
    uploadProgress(fileList) {
      console.log(fileList.file)
    },

    // 上传成功
    uploadChange(response) {
      const self = this;
      if (!!response && (response.status) === 0) {
        let quill = self.$refs.editor.quill
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', `${response.data}`)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        // 提示信息，需引入Message
        console.log('图片插入失败！')
      }
    },

    // 值发生变化
    handleEditorChange(editor) {
      this.$emit('backContent', (editor.html))
    },

    // 取消图片弹层
    handleCancel() {
      console.log('handleCancel')
      Reflect.set((this.pictureInfo), 'visible', false);
    },

    //图片弹层的确定
    handlePictureSure(val) {
      const self = this;
      if (!!val) {
        let quill = self.$refs.editor.quill
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', `${val}`)
        // 调整光标到最后
        quill.setSelection(length + 1);
        Reflect.set((this.pictureInfo), 'visible', false);
      } else {
        self.$message({
          message: '很抱歉，图片插入失败!',
          type: 'warning'
        });
      }
    },

  },

  watch: {
    // 写入文本域内容
    contentInfo: {
      handler: async function (val) {
        if (!!val) {
          this.content = val;
        }
      },
      deep: true,
      immediate: true,
    },
  }
}
</script>

<style lang="scss" scoped>
@import "assets/style";
</style>